package com.limuzi.util;

import com.alibaba.fastjson.JSONObject;
import com.limuzi.model.PushMsgRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: limuzi
 * @create: 2023-06-26
 */
@Component
@Slf4j
public class DingTalkSendMsgUtils {
    // 配置自己的钉钉群webhook
    public static String URL = "https://oapi.dingtalk.com/robot/send?access_token=534bc53c737c0b614b881e57303c60ac884f8f9129e18abed1f7f29389fed5a5";

    public static String DIYURL = "https://oapi.dingtalk.com/robot/send?access_token=194662f6d44925bdf4410ca436fcb3eea52d2c863b0369588033c1a614c4c967";

    public static void  sendPushMsg(PushMsgRequest msg){
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgtype","text");
            JSONObject subJsonObject = new JSONObject();
            subJsonObject.put("content","[你有新消息啦]\n" +msg.getMsg());
            jsonObject.put("text",subJsonObject);
            Map<String,String> headersMap = new HashMap<>();
            headersMap.put("Content-Type", "application/json");
            HttpRequestUtils.httpPostJson(DIYURL,jsonObject.toJSONString(),headersMap);


        }catch (Exception e){
            log.error("消息推送钉钉msg发送异常",e);
        }
    }
    public static void sendToDingTalk(Exception exception){
        try{
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);

            exception.printStackTrace(pw);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgtype","text");
            JSONObject subJsonObject = new JSONObject();
            subJsonObject.put("content","[LTID:"+ MDC.get("traceId") +"]\n" +sw);
            jsonObject.put("text",subJsonObject);
            Map<String,String> headersMap = new HashMap<>();
            headersMap.put("Content-Type", "application/json");
            HttpRequestUtils.httpPostJson(URL,jsonObject.toJSONString(),headersMap);
        }catch (Exception e){
            log.error("消息推送钉钉发送异常",e);
        }
    }
}
